package com.example.lotterysystem.common.util;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    private JacksonUtil(){
        //私有化构造
    }
    //单例
    private final static ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = new ObjectMapper();
    }

    public static ObjectMapper getObjectMapper(){
        return OBJECT_MAPPER;
    }

    private static  <T> T tryParse(Callable<T> parser) {
        return tryParse(parser,JacksonException.class);
    }

    private static  <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        //处理异常
        try {
            return parser.call();
        } catch (Exception var4) {
            if (check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            }
            throw new IllegalStateException(var4);
        }
    }

    /**
     * 序列化(将所有形式的对象全部转换为String类型进行存储)
     * 在序列化的时候所有形式的对象的序列化都是一样的,只有在反序列化时,才会有区别
     * @param object
     * @return
     */
    public static String writeValueAsString(Object object){
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().writeValueAsString(object);
        });
    }


    /**
     * 反序列化
     * @param content
     * @param valueType
     * @return
     */
    public static <T> T readValue(String content,Class<T> valueType){
        return JacksonUtil.tryParse(()->{
           return JacksonUtil.getObjectMapper().readValue(content,valueType);
        });
    }


    /**
     * 反序列化 列表
     * list的反序列化是必须要构造一个JavaType的
     * @param content
     * @param paramClasses
     * @return
     */
    public static <T> T readListValue(String content,Class<?> paramClasses){
        JavaType javaType = JacksonUtil.getObjectMapper().getTypeFactory()
                .constructParametricType(List.class,paramClasses);
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(content,javaType);
        }) ;
    }
}
